from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *
from django.db.models import F


class UserListView(APIView):

    def get(self, request):
        queryset = User.objects.all()
        ser = UserSerializer(queryset, many=True)
        return Response(ser.data)

    def put(self, request):
        id = request.data.get("id")
        try:
            User.objects.filter(id=id).update(level=2)
            # 进行 用户表与 优惠券的关联

            coupons = Coupon.objects.all()
            data_list = []
            for coupon in coupons:
                User_Coupon.objects.create(user_id=id, coupon_id=coupon.id)
                # data_list.append(User_Coupon(user_id=id, coupon_id=coupon.id))
            # User_Coupon.objects.bulk_create(data_list)

            return Response({"msg": '更新数据', "status": 200})
        except Exception as e:
            print(e)
            return Response({"msg": '更新失败', "status": 500})


class GoodsView(APIView):

    def get(self, request):
        queryset = Goods.objects.all()
        ser = GoodsSerializer(queryset, many=True)
        return Response(ser.data)

    def put(self, request):
        id = request.data.get("id")
        Goods.objects.filter(id=id).update(store=F("store") - 1)

        return Response({"msg": "更新库存"})


class LoginView(APIView):

    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")

        user = User.objects.filter(username=username, password=password).first()
        if user:
            return Response({"msg": "登录成功", "status": 200, "username": username, "uid": user.id})
        else:
            return Response({"msg": "登录失败", "status": 500})


class CouponView(APIView):

    def get(self, request):
        uid = request.GET.get("uid")

        queryset = User_Coupon.objects.filter(user_id=uid)

        ser = UserCouponSerializer(queryset, many=True)

        return Response(ser.data)
